using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Isis.Extensions
{
    public static class SerializationExtensions
    {
        /// <summary>
        /// Gets an approximate size of an object.
        /// Does not work on value types.
        /// Throws an exception if the class is not marked as serializable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static long GetObjectSize<T>(this T value)
            where T : class, new()
        {
            if (value == null) return 0;
            MemoryStream stream = BinarySerialize(value);
            return stream.Length;
        }

        /// <summary>
        /// Serialize object into a memory stream using Binary Serialization
        /// </summary>
        /// <param name="objectToSerialize">object to serialize</param>
        /// <returns></returns>
        internal static MemoryStream BinarySerialize(object objectToSerialize)
        {
            var m = new MemoryStream();
            var b = new BinaryFormatter();

            b.Serialize(m, objectToSerialize);

            return m;
        }
    }
}